package com.poem.springboot_rear.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.poem.springboot_rear.common.LogAs;
import com.poem.springboot_rear.common.LogType;
import com.poem.springboot_rear.common.Result;
import com.poem.springboot_rear.entity.Address;
import com.poem.springboot_rear.mapper.AddressMapper;
import com.poem.springboot_rear.service.AddressService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 功能：
 * 作者： 小祝小祝
 * 日期： 2023/11/20 16:03
 */
@CrossOrigin
@RestController
@RequestMapping("/address")
public class AddressController {

    @Resource
    AddressService addressService;

    /**
     * 新增地址
     */
    @LogAs(operation = "新增地址", type = LogType.ADD)
    @PostMapping("/add")
    public Result add(@RequestBody Address address) {
        try {
            addressService.save(address);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据库错误");
            } else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }

    /**
     * 修改地址
     */
    @LogAs(operation = "修改地址", type = LogType.UPDATE)
    @PutMapping("/update")
    public Result update(@RequestBody Address address) {
        try {
            addressService.updateById(address);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据库错误");
            } else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }

    /**
     * 删除单个地址
     */
    @LogAs(operation = "删除单个地址", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        addressService.removeById(id);
        return Result.success();
    }

    /**
     * 批量删除地址
     */
    @LogAs(operation = "批量删除地址", type = LogType.BATCH_DELETE)
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        addressService.removeBatchByIds(ids);
        return Result.success();
    }

    /**
     * 分页查询
     */
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageIndex,
                               @RequestParam Integer pageSize,
                               @RequestParam String name) {
        // 创建一个条件构造器
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        Page<Address> page = addressService.page(new Page<>(pageIndex, pageSize), queryWrapper);
        return Result.success(page);
    }
}
